import { HttpException } from '@nestjs/common';
import { EntityNotFoundError } from '@loopback/repository';

export const ErrorCodes = {
  UnknownError: 20,
  DBOPFailed: 11,
  ValidationError: 22,
  ObjectNotFound: 6,
  NotSupport: 2,
  MsgTimeOut: 8,
  ForbidBatchDel: 23,
  NotSupportModifyType: 24,
  InvalidField: 25,
  ForbidModify: 26,
  FieldRequired: 27,
  ReadFile: 28,
  XmlParse: 29,
  Upload: 30,
  ServiceFailed: 31,
  PlanEnable: 16,
  FobidDelete: 33,
  AccountLocked: 66,
  MqttParse: 13,
  ChildrenExist: 48,
  NoParentNode: 49,
  AutoUpdateFail: 10002,
  DuplicateName: 68,
  DuplicateID: 74,
  InvalideDate: 69,
  EmptyItems: 70,
  InvalidDevices: 71,
  NoGateway: 72,
  DevExcuteFailed: 18,
  EnableFailed: 76,
  AddDevFailed: 75,

  // loopback错误 code重定义
  LoginFailed: 51,
  InvalidToken: 52,
  KeyNotFound: 54,
  AccessDenied: 57,
  AuthorizationRequired: 58,
  ModelNotFound: 59,
  PasswordChangeNotAllowed: 60,
  PasswordTooLong: 61,
  InvalidPassword: 62,
  UserNotFound: 66,
  ParamError: 1,
  InvalidSsgw: 79,
  InvalidPlan: 365,
  PlanPending: 81,
  AssetExist: 82,
}
;
export class AppError {
    code: any;
    statusCode: any;
    name: string;
    message: string;
    constructor(err, code: number, statusCode ?: number, name ?: string ) {
      if (typeof err === 'string') {this.message = err; }
      else if (err.message) {this.message = err.message; }
      else {this.message = err; }
      this.name = name || 'ApplicationError';
      this.code = code;
      this.statusCode = statusCode || 406;
    }
}

export function transError(exception: unknown): AppError {
  if (exception instanceof HttpException) {
      const message = exception.message;
      return new AppError(message, ErrorCodes.UnknownError, exception.getStatus());
   }
  if (exception instanceof AppError) {
       return exception;
   }
  if (exception instanceof EntityNotFoundError) {
      return new AppError(exception.message, ErrorCodes.ModelNotFound, 404);
   }
  if (exception instanceof Error) {
       return new AppError(exception.message, ErrorCodes.UnknownError);
   }
  return new AppError(String(exception) || 'unknow error', ErrorCodes.UnknownError);
}
